<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api;

use App\Models\ShopMemberRole;
use App\Repositories\Api\MemberRepository;
use App\Repositories\Api\ProductRepository;
use App\Repositories\Api\ShopRepository;
use App\Repositories\Manage\StatRepository;
use App\Repositories\ParkRepository;

class ShopController extends MiniAppController
{

    private $shopRepo = NULL;

    public function __construct(
        ShopRepository $shopRepo
    )
    {
        parent::__construct();
        $this->shopRepo = $shopRepo;
    }

    public function index()
    {
        $filter = request()->all();
        $member_types = (new MemberRepository())->getTypes(UID);
        settype($member_types, "array");
        $member_types[] = 0;

        $this->pageSize = 30;

        $filter['shopIds'] = ShopMemberRole::query()->whereIn("role_id", $member_types)->pluck("shop_id")->toArray();
        $res = $this->shopRepo->getList($filter, $this->pageNum, $this->pageSize);

        return retSuc($res);
    }

    /**
     * 搜索
     */
    public function search()
    {
        $filter = request()->all();
        $filter['shopIds'] = (new ProductRepository())->getShopIdsByWord(trim($filter['keywords'] ?? ""));
        $res = $this->shopRepo->getSearchList($filter, $this->pageNum, $this->pageSize);
        return retSuc($res);
    }

    public function update($id = null)
    {
        $data = request()->only(['id', 'contact_name', 'title', 'contact_phone', 'status']);
        $last_id = $this->shopRepo->saveOrUpdate($data, $id ?? 0);
        if (!$last_id) {
            return retFail(empty($data['id']) ? "新增失败" : "更新失败");
        }
        $res = $this->shopRepo->getOne($last_id);
        return retSuc($res);
    }

    public function detail($id)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");
        $res = $this->shopRepo->getOne($id);
        return retSuc($res);
    }

    public function delete($id)
    {
        $id = intval($id);
        if (empty($id)) {
            return retFail("参数错误");
        }

        return $this->shopRepo->deleteShop($id);
    }

    /**
     *店铺统计
     */
    public function stat()
    {
        (new StatRepository())->getMonthStat();
    }

    /**
     * 园区
     */
    public function park_list()
    {
        return retSuc([
            'parks' => (new ParkRepository())->getParks()
        ]);
    }


}
